﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using JHT.SimpleTaskSystem.Dto;
using JHT.SimpleTaskSystem.IRepository;

namespace JHT.SimpleTaskSystem
{
    public class TaskAppService : SimpleTaskSystemAppServiceBase, ITaskAppService
    {
        private readonly IRepository<SimpleTask, long> taskRepository;
        private readonly ITaskRepository myTaskRepository;
        public TaskAppService(IRepository<SimpleTask, long> taskRepository, ITaskRepository myTaskRepository)
        {
            this.taskRepository = taskRepository;
            this.myTaskRepository = myTaskRepository;
        }


        public void CreateTask(CreateTaskInput input)
        {
            Logger.Info("Creating a new task with description: " + input.Description);

            taskRepository.InsertAndGetId(AutoMapper.Mapper.Map<SimpleTask>(input));
        }

        public GetTaskOutput GetSimpleTasks(GetTasksInput input)
        {
            GetTaskOutput getTaskOutput = new GetTaskOutput();
            var result = myTaskRepository.GetAllWithPeople(input.AssignedPersonId, input.State);
            getTaskOutput.Tasks = AutoMapper.Mapper.Map<List<TaskDto>>(result);
            return getTaskOutput;
        }

        public void UpdateTask(UpdateTaskInput input)
        {
            var dbTask = myTaskRepository.Get(input.TaskId);
            if (input.AssignedPersonId.HasValue)
            {
                dbTask.AssignedPersonId = input.AssignedPersonId;
            }

            if (input.State.HasValue)
            {
                dbTask.State = input.State.Value;
            }

            // 我们无需使用repository.Update方法，因为默认所有的应用服务为‘unit of work’
            // Abp会自动保存所有修改，当在‘unit of work’结束时
        }

    }
}
